/**
 * Created by hjqi on 2016/1/13.
 */

var express = require('express');
var router = express.Router();
var job_collection_name = require('../lib/config/config').config.mongodb.job_collection;
var mongodb = require('../db/mongodb');
var __db = new mongodb(job_collection_name);

router.get('/get',function(req, res, next){
    var db = req.db;
    var _user = req.username;
    var param = req.query;
    __db.getWithParam(db,{"username":_user,"id":param.id},cb);

    function cb(err,one){
        if (err)
            res.send(err);
        else
            res.send(one);
    }
});

router.post('/getWithParam',function(req, res, next){
    var db = req.db;
    //var _user = req.username;
    var param = req.body;
    param.username = req.username;
    __db.getWithParam(db,param,cb);

    function cb(err,one){
        if (err)
            res.send(err);
        else
            res.send(one);
    }
});

router.get('/getall',function(req, res, next){
    var db = req.db;
    var _user = req.username;
    __db.getWithParam(db,{"username":_user},cb);
    function cb(err,one){
        if (err)
            res.send(err);
        else
            res.send(one);
    }
});

router.post('/insert',function(req, res, next){
    var db = req.db;
    var data =  req.body;
    __db.insert(db,data,cb);

    function cb(err) {
        if (err)
            res.send(err.message);
        else
            res.send("true");
    }
});

router.post('/update',function(req, res, next){
    var db = req.db;
    var _user = req.username;
    var data = req.body;
    __db.updateWithParam(db,{"username":_user,"id":data.id},data,cb);

    function cb(err) {
        if (err){
            var result = {
                ret:false,
                error:err ,
                data: err
            }
            res.send( result );
        } else{
            var result = {
                ret:true,
                error:null ,
                data: "true"
            }
            res.send( result );
        }
    }
});

router.get('/delete',function(req, res, next){
    var db = req.db;
    var _user = req.username;
    var param = req.query;
    __db.delWithParam(db,{"username":_user,"id":param.id},cb);

    function cb(err) {
        if (err)
            res.send(err);
        else
            res.send("true");
    }
});

module.exports = router;
//record the operation  info of the service of (stopping\starting\updating etc)
//just an another minimum ckcest 16/11/24
